import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/recorder.dart';
import 'package:ichinesereader/pages/book/bookQuizEditor.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/writing.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
import '../../controller/books.dart';
import '../../controller/cache.dart';
import '../../controller/user.dart';
import '../../widgets/dialogs/addToFolderDialog.dart';

class BookBar extends StatefulWidget {
  const BookBar({
    Key? key,
    required this.bookId,
    required this.assignmentId,
    required this.readingType,
    required this.bookCode,
    this.bookTitle,
    this.userName,
  }) : super(key: key);
  final String bookId;
  final String assignmentId;
  final NanhaiBookReadingTypes readingType;
  final String bookCode;
  final String? bookTitle;
  final String? userName;
  @override
  _BookBar createState() => _BookBar();
}

class _BookBar extends State<BookBar> {
  ValueNotifier quizNotifier = ValueNotifier(false);
  late Timer periodicTimer;
  final BooksController _booksController = Get.find();
  final UserController _usersController = Get.find();
  final RecorderController _recorderController = Get.put(RecorderController());
  final box = Hive.box('appconfig');

  @override
  void initState() {
    super.initState();
    periodicTimer = Timer(Duration(milliseconds: 1), () {});

    if (box.get(CacheManagerKey['_quizAvailable'].toString())) {
      periodicTimer = Timer.periodic(
        const Duration(seconds: 2),
        (timer) {
          periodicTimer = timer;
          if (box.get(CacheManagerKey['_readComplete'].toString()) &&
              quizNotifier.value == false) {
            Future.delayed(const Duration(milliseconds: 1000), () {
              quizNotifier.value = true;
              timer.cancel();
            });
          }
          if (quizNotifier.value == false) {
            if (box.get(CacheManagerKey['_isFinished'])) {
              Future.delayed(const Duration(milliseconds: 3000), () {
                quizNotifier.value = true;
                timer.cancel();
              });
            }
          }
        },
      );
    }
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Student ||
        box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Individual) {
      _recorderController.fetchBookRecordingFile(
          widget.bookId, widget.assignmentId);
    }

    // _recorderController.audioBytes.clear();
    // _recorderController.getBookRecordingFileBytes(
    //     widget.bookId, widget.assignmentId);
  }

  @override
  void dispose() {
    super.dispose();
    periodicTimer.cancel();
  }

  Widget build(BuildContext context) {
    Log.debug('start building book bar');
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Row(
        children: [
          MouseRegion(
            cursor: SystemMouseCursors.click,
            child: ValueListenableBuilder(
              valueListenable: quizNotifier,
              builder: (context, value, child) {
                return Visibility(
                    visible: value as bool,
                    child: SizedBox(
                      width: 45.0,
                      height: 45.0,
                      child: PointerInterceptor(
                        intercepting: true,
                        child: GestureDetector(
                          // backgroundColor: Theme.of(context).primaryColorDark,
                          // foregroundColor: Get.isDarkMode
                          //     ? Colors.black
                          //     : Theme.of(context).primaryColorLight,
                          onTap: () {
                            Navigator.of(context).pop();
                            _usersController.refreshLevelPercentage();
                            _booksController.updateBookStatus(
                                widget.bookId.toString(), widget.readingType);
                            Get.to(() => BookQuizEditor(
                                  bookId: widget.bookId,
                                  bookcode: widget.bookCode,
                                  bookTitle: widget.bookTitle,
                                  assignmentId: widget.assignmentId,
                                ));
                            // Get.to(() => InAppWebViewAppBookQuizScreen(
                            //       bookCode: widget.bookCode,
                            //       bookId: widget.bookId,
                            //       bookTitle: widget.bookTitle,
                            //       assignmentId: widget.assignmentId,
                            //       readingType: widget.readingType,
                            //     ));
                          },
                          child: Icon(Icons.quiz_outlined,
                              color: Colors.white, size: 35),
                        ),
                      ),
                    ));
              },
            ),
          ),
          const SizedBox(width: 15),
          MouseRegion(
              cursor: SystemMouseCursors.click,
              child: GestureDetector(
                child: Icon(Icons.mic, color: Colors.white, size: 40),
                onTap: () {
                  // _recorderController.fetchBookRecordingFile(
                  //     widget.bookId, widget.assignmentId);
                  _booksController.setShowBookBarRecord();
                },
              )),
          const SizedBox(width: 15),
          MouseRegion(
              cursor: SystemMouseCursors.click,
              child: GestureDetector(
                child: Icon(Icons.edit, color: Colors.white, size: 35),
                onTap: () {
                  _booksController.closeToggles();
                  showGeneralDialog(
                      context: context,
                      transitionDuration: Duration(milliseconds: 0),
                      pageBuilder: (bc, ania, anis) {
                        return MyWriting(
                          bookId: widget.bookId,
                          assignmentId: widget.assignmentId,
                        );
                      });
                },
              )),
          const SizedBox(width: 15),
          MouseRegion(
              cursor: SystemMouseCursors.click,
              child: GestureDetector(
                child: Icon(Icons.add, color: Colors.white, size: 45),
                onTap: () {
                  _booksController.closeToggles();
                  _booksController.fetchBookAllFolders();
                  List<String> bookids = [];
                  bookids.add(widget.bookId);
                  showGeneralDialog(
                      context: context,
                      transitionDuration: Duration(milliseconds: 0),
                      pageBuilder: (bc, ania, anis) {
                        return AddToFolderDialog(
                            readingType: widget.readingType,
                            title: 'Add to folder',
                            selected: bookids,
                            message: '',
                            readingTypeFrom: '');
                      });
                },
              )),
          const SizedBox(width: 15),
          if (widget.assignmentId == '')
            MouseRegion(
                cursor: SystemMouseCursors.click,
                child: GestureDetector(
                  child: Icon(Icons.settings, color: Colors.white, size: 35),
                  onTap: () {
                    _booksController.setShowBookBarSetting();
                  },
                )),
        ],
      ),
    );
  }
}
